package middleware

import (
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/gjwt"
	"duoke/utils/response"
	"duoke/utils/yaml"
	"github.com/gin-gonic/gin"
)

func MpAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 登录验证
		utoken := c.Request.Header.Get("D-Token-C")
		if utoken == "" {
			utoken = c.DefaultQuery("token", "")
		}
		if utoken == "" {
			response.Response(c, 50008, "无权限访问", nil)
			c.Abort()
			return
		}
		acid := c.Request.Header.Get("D-Acid")
		if acid == "" {
			acid = c.DefaultQuery("acid", "")
		}
		if acid == "" {
			response.Error(c, "请配置小程序ACID", nil)
			c.Abort()
			return
		}
		result, err := gjwt.Parse(utoken)
		if err != nil {
			response.Response(c, 50008, err.Error(), nil)
			c.Abort()
			return
		}
		config := yaml.GetConfig()
		if config.Request.Debug == "false" {
			if result.Url != config.Request.Domain {
				response.Response(c, 50008, "请重新登录1", nil)
				c.Abort()
				return
			}
		}
		if result.Uid == 0 {
			response.Response(c, 50008, "请重新登录", nil)
			c.Abort()
			return
		}
		// 初始化全局账户信息
		c.Set("uid", result.Uid)
		c.Set("account", service.AccountStruct{Id: 1})
		c.Set("user", service.UserStruct{Id: result.Uid, Acid: gconv.Int(acid)})
		c.Next()
	}
}
func NotAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 登录验证
		utoken := c.Request.Header.Get("D-Token-C")
		if utoken == "" {
			utoken = c.DefaultQuery("token", "")
		}
		acid := c.Request.Header.Get("D-Acid")
		if acid == "" {
			acid = c.DefaultQuery("acid", "")
		}
		if acid == "" {
			response.Error(c, "请配置小程序ACID", nil)
			c.Abort()
			return
		}
		var user_id int
		if utoken != "" {
			result, err := gjwt.Parse(utoken)
			if err != nil {
				response.Response(c, 50008, err.Error(), nil)
				c.Abort()
				return
			}
			if result.Uid == 0 {
				response.Response(c, 50008, "请重新登录", nil)
				c.Abort()
				return
			}
			user_id = result.Uid
			// 初始化全局账户信息
		} else {
			user_id = 0
		}
		c.Set("uid", user_id)
		c.Set("account", service.AccountStruct{Id: 1})
		c.Set("user", service.UserStruct{Id: user_id, Acid: gconv.Int(acid)})
		c.Next()
	}
}
